package com.wzgl.core.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.wzgl.core.model.Tusers;
import com.wzgl.core.utils.MessageEnum;

/***
 * ajax请求 验证用户登录 
 * @author Administrator
 *
 */
public class RequiredUserIdInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		// TODO Auto-generated method stub
		/***
		 * 针对需要登录的跳转增加用户登录验证
		 * 1、必须使用$.post提交,$.ajax request.getParameter获取不到参数
		 * 2、通过getHeader判断请求类型 post提交和controller.render
		 * 3、ajax提供josn消息、controller.render重新跳转至首页
		 * 4、通过验证执行下一步.
		 */
		 JSONObject json = new JSONObject();
		 Controller controller = inv.getController();
		 HttpServletRequest request = controller.getRequest();
		 System.out.println("bengin DdgRequiredUserIdInterceptor ----------------------");
		 String header = request.getHeader("X-Requested-With");  
		 
		 Tusers user = InterUtils.tryToGetUser(inv);
		 if (user != null) {
			controller.setAttr("fnickname", user.getFnickname());
			inv.invoke();
		 } else {
			 boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);  
			 if(isAjax){
    			 json.clear();
      			 json.put("errorCode", MessageEnum.PARAM_ERROR.getRetCode());
      			 json.put("message", MessageEnum.NO_LOGIN.getRetMess());
      			 controller.renderJson(json.toJSONString());
    		 }else{
    			 controller.render("login.jsp");
    		 }
		 }
        
	}

}
